package com.sptpc.demo.controller;

import com.sptpc.demo.controller.requests.ModifyDrinkRequest;
import com.sptpc.demo.model.Drink;
import com.sptpc.demo.service.impl.IDrinkService;
import lombok.extern.slf4j.Slf4j;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;


@Slf4j
@RestController
@RequestMapping("/drink")
public class DrinkController {
    @Autowired
    public IDrinkService drinkService;
    //    get /drink/
//    @RequestMapping(value = "/",method = RequestMethod.GET)
//    查询所有
    @GetMapping("/")
    public List<Drink> getAll(){
//        后期从数据库查询
//        ArrayList<Drink> result = new ArrayList<>();
//        Drink drink1 = new Drink();
//        drink1.setId(1);
//        drink1.setName("茉莉绿茶");
//        drink1.setPrice(BigDecimal.valueOf(8.00));
//        Drink drink = Drink.builder()
//                .id(1).name("茉莉绿茶")
//                .price(BigDecimal.valueOf(8.00)).build();

//        result.add(Drink.builder()
//                .id(1)
//                .name("茉莉花茶")
//                .price(Money.parse("USD 8.00"))
//                .build());
//        result.add(Drink.builder()
//                .id(2)
//                .name("焦糖拿铁")
//                .price(Money.parse("USD 12.00"))
//                .build());
        List<Drink> all = drinkService.getAllDrinks();
        return all;
    }

    /**
     * 查询指定饮品
     * get /drink/1
     * get /drink/?id=1
     * 日志 log4j
     */
    @GetMapping("/{id}")
    public Drink getDrink(@PathVariable Integer id){
        log.info("要查询的饮品id: {}",id);
//        后期从数据库查询
        Drink drink=Drink.builder()
                .id(1)
                .name("茉莉花茶")
                .price(Money.parse("USD 8.00"))
                .build();
        return drink;
    }

    /**
     * 新建
     * post /drink/ {"name":"奶茶","price":"8.00"}
     * 传参思路：
     * 1.直接使用实体类
     * 2.根据前端参数内容编写TO类
     */

    @PostMapping("/")
    public Drink addNewDrink(@RequestBody @Valid Drink drink,
                             BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            for (ObjectError error : bindingResult.getAllErrors()) {
                log.error(error.toString());
            }
            return null;
        }else {
            log.info("新增饮品：{}", drink);
//        后期 insert 数据库
//            Drink drink1 = Drink.builder()
//                    .id(1)
//                    .name("茉莉花茶")
//                    .price(Money.parse("USD 8.00"))
//                    .build();
            drinkService.addNewDrink(drink);
            return drink;
        }
    }

    /**
     * 修改
     * put /drink/ {"id":1,"name":"新奶茶","price":"8.00"}
     */

    @PutMapping("/")
    public Drink modifyDrink(@RequestBody ModifyDrinkRequest request){
        log.info("修改饮品：{}", request);
//        后期 updata 数据库
//        Drink drink1=Drink.builder()
//                .id(1)
//                .name("茉莉花茶")
//                .price(Money.parse("USD 8.00"))
//                .build();
//        1.查看有无该饮品
        Drink drink = drinkService.getDrinkById(request.getId());
//        2.把要修改的内容-》drink对应属性
//        if (request.getName()!=null && !request.getName().equals("")) {
//            drink.setName(request.getName());
//        }
        BeanUtils.copyProperties(request,drink);
//        3.更新数据库
        drinkService.updateDrink(drink);
        return drink;
    }

    /**
     * 删除
     * delete /drink/1
     */

    @DeleteMapping("/{id}")
    public String deleteDrink(@PathVariable Integer id){
        log.info("要删除的饮品id：{}", id);
        drinkService.deleteDrinkById(id);
        return "删除操作成功";
    }

    /**
     * 文件上传
     * 前端必须使用multipart/form-data
     */
    @PostMapping(value = "/upload",
            consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
    public String uploadFile(MultipartFile file){
        String path = "D:/upload/";
        String filePath=file.getOriginalFilename();
        File saveFile=new File(filePath);
        try {
            file.transferTo(saveFile);
        } catch (IOException e) {
            e.printStackTrace();
            return "上传失败";
        }
        return "上传成功";
    }



    /**
     * 批量创建饮品
     */
    @PostMapping(value = "/batch",consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
    public List<Drink> batchAddNewDrinks(MultipartFile file){
        List<Drink> results=new ArrayList<>();
        try {
//            InputStream inputStream=file.getInputStream();
//            InputStreamReader inputStreamReader=new InputStreamReader(inputStream);
//            BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
            BufferedReader reader=new BufferedReader(new InputStreamReader(file.getInputStream()));
            String line="";
            while ((line=reader.readLine())!=null){

//                解析每一行
                String[] args = line.split(",");

                results.add(Drink.builder()
                        .id(Integer.parseInt(args[0]))
                        .name(args[1])
                        .price(Money.of(CurrencyUnit.of("CNY"), Double.parseDouble(args[2])))
                        .build());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return results;
    }
}

